﻿using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using ImageHandler.Framework;
using ImageHandler.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace ImageHandler.ViewModels
{
    public class HomeViewModel : ObservableObject
    {

        private PartItemModel _currentPart;

        public PartItemModel CurrentPart
        {
            get { return _currentPart; }
            set
            {
                SetProperty(ref _currentPart, value);
            }
        }

        public ObservableCollection<string> Logs { get; set; }
        public ObservableCollection<PartItemModel> Parts { get; set; }
        public RelayCommand<string> OperateCommand { get; set; }

        public HomeViewModel()
        {
            Logs = new ObservableCollection<string>();
            Parts = new ObservableCollection<PartItemModel>();
            OperateCommand = new RelayCommand<string>(Execute);

            var partViewModels = ReflectionHelper.GetDerivedTypes<PartViewModel>();
            foreach (var part in partViewModels)
            {
                var viewModel = (PartViewModel)Activator.CreateInstance(part);
                viewModel.OperateLogAction = (msg) => Logs.Add($"{CurrentPart.ViewModel} - {msg}");

                var viewName = viewModel.GetType().FullName.Replace("ViewModel", "View");
                var view = ReflectionHelper.CreateInstance<UserControl>(viewName, null);
                view.DataContext = viewModel;
                Parts.Add(new PartItemModel() { ViewModel = viewModel , View = view});
            }
            CurrentPart = Parts.FirstOrDefault();
        }

        private void Execute(string action)
        {
            if (action == "ClearLogs")
            {
                Logs.Clear();
                return;
            }
        }
    }
}
